import os
import re
from datetime import datetime
from openpyxl import Workbook


"""生成接口文档"""

dir = r'/testcase'
# 绝对路径
paths = []
# 文件名
file_name = []
#------------------------Excel设置------------------------
# 创建工作簿
book = Workbook()
# 引用工作簿
sheet = book.active
# 表头
sheet.append(["接口名称", "接口脚本名称", "接口脚本类型", "是否执行", "执行顺序", "接口访问地址", "接口参数", "返回值"])
# 计数（行）
i = 2
# 接口名称、接口脚本名称、接口访问地址、接口参数所在列
jkmc = 1
jbmc = 2
fwdz = 6
jkcs = 7
# 定义保存路径
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
today = datetime.now().strftime('%Y-%m-%d')
save_path = os.path.join(desktop_path, f"接口文档{today}.xlsx")


#------------------------程序读写------------------------
# 获取绝对路径
for root,dirs,files in os.walk(dir):
    # file就是文件名，对应
    for file in files:
        # 拼出绝对路径
        absolute_path = os.path.join(root, file)
        # 读取所有Python文件、获取文件名
        if absolute_path.endswith(".py") and "__init__.py" not in absolute_path :
            file_name.append(file)  #------------------------------------------【接口脚本名称】
            paths.append(absolute_path)
            # 写数据
            sheet.cell(row=i, column=jbmc).value = file_name[i-2]

            with open(absolute_path, "r", encoding="utf-8") as f:
                content = f.read()
                lines = content.splitlines()
                for line in lines:
                    if "url = getter.getUrl" in line:
                        line = line.strip()
                        url_name = line[21:-2]
                        # 在tyturl.py文件中查找url
                        with open("/testdata/tyturl.py", "r", encoding="utf-8") as u:
                            for l in u:
                                l1 = l.split("\"")
                                if url_name in l1:
                                    l = l.strip()
                                    last_quote = l.rfind('"')  # 最后一个引号的位置
                                    second_last_quote = l.rfind('"', 0, last_quote)  # 倒数第二个引号的位置
                                    url = l[second_last_quote + 1: last_quote]
                                    # 写数据
                                    sheet.cell(row=i, column=fwdz).value = url
                    # 截取title
                    if "@allure.title" in line:
                        title = line[15:-2]  # --------------------------------【接口名称】
                        # 写数据
                        sheet.cell(row=i, column=jkmc).value = title

                # 提取body中的参数
                # 匹配body的格式，包括换行符在内
                pattern = r'body\s*=\s*(\{[\s\S]*?\})'
                match = re.search(pattern, content)
                if match:
                    body_str = match.group(0).replace(" ", "")
                    match = re.search(r'body\s*=\s*\{([^}]*)\}', body_str)

                    if match:
                        body_str = match.group(1)
                    pattern = r'"([^"]+)":([^,]+)'
                    pairs = re.findall(pattern, body_str)

                    result = {}
                    for key, value in pairs:
                        # 去掉括号（如 `fundcode()` → `fundcode`）
                        cleaned_value = re.sub(r'\(\)$', '', value.strip())
                        result[key] = cleaned_value
                    # 入参，做了换行排列
                    pars = '\n'.join(result.keys())  # -------------------------【接口参数】
                    # 写数据
                    sheet.cell(row=i, column=jkcs).value = pars
                    i = i + 1
                # 保存表格
                if os.path.exists(save_path):
                    os.remove(save_path)
                book.save(save_path)
        else:
            continue

#------------------------Excel生成完毕------------------------
print("\n\n-----------excel生成完毕-----------\n位置：" + desktop_path)